<template>
	<m-layout class="dialogue" :title="touserName" gap="47 24 120 24">

		<!-- 加载更多 -->
		<m-loading gap="100 0" :list='listArr' :index="pageIndex" :total="totalPage" :loading="isLoading" :isEmpty="false" />
		<view class="dleList">
			<view :class="'delI'+item.messageID" v-for="item in listArr" :id="item.VIEW_ID" :key="item.VIEW_ID">
				<dialogue-list :item="item" :touserName="touserName" :touserHeadpic="touserHeadpic"></dialogue-list>
			</view>
		</view>

		<!-- 底部 -->
		<view class="footers flex">
			<view class="input_v">
				<textarea type="text" class="dle_input" v-model="msg" :auto-height="true" placeholder="请输入"
					placeholder-class="placeholderClass" />
			</view>
			<m-icon @click="addPhoto" size="50" spa="0 0 0 23" color="#FFCE41" type="icon_xj" />
			<m-button size="small" type="primary" @click="submit(1)">发送</m-button>
		</view>
		<template v-if="unreadNumber>0">
			<view @click="scrollToBottom(99999)" class="dleUnread">未读条数{{unreadNumber}}</view>
		</template>

	</m-layout>
</template>

<script>
	// import {
	// 	formatDate
	// } from '@/utils/digit.js'
	import {
		mapState
	} from 'vuex'
	// import {
	// 	GetMsg,
	// 	sendMsg,
	// 	ReadAll,
	// 	Ws
	// } from "@/api/chatMessage.js" // 引入接口
	// import {
	// 	UploadImageFile
	// } from '@/api/ExcuteUploadFile.js'
	// import {
	// 	wsUrl
	// } from '@/common/baseconfig.js'
	// import {
	// 	getToken
	// } from '@/utils/auth.js'
	// import {
	// 	isEmpty
	// } from "@/utils/verify.js";
	// import WebSocketClass from '@/utils/WebSockets.js'
	export default {
		computed: {
			...mapState({
				userinfo: state => state.user.userinfo
			})
		},
		data() {
			return {
				touserid: 0,
				touserName: '',
				msg: '',
				img: '',
				type: 1, // 1文字；2图片；3订单；4商品

				// 列表
				pageIndex: 1,
				PageSize: 10,
				totalPage: 0,
				isLoading: true,
				listArr: [],

				unreadItem: [], // 未读数据
				newMsgID: '', // 最新一条数据ID
				unreadNumber: 0, // 未读条数
				
				touserHeadpic: '', // 聊天方头像
			};
		},
		watch: {
			listArr(val) {
				this.isUnreadItem(val);
			}
		},
		onLoad({
			touserid,
			touserName,
			touserHeadpic
		}) {
			this.touserid = touserid;
			this.touserName = touserName;
			if(touserHeadpic){
				this.touserHeadpic = touserHeadpic;
			}
		},
		onShow() {
			this.init();
			this.ReadAll();
			// this.getChatRecord();
			this.getDialogueMsg();
		},
		onReachBottom() {},
		destroyed() {
			this.ReadAll();
		},
		onPageScroll(e) {
			// 如果滚动条在顶部  加载更多
			if (e.scrollTop == 0) {
				if (this.pageIndex <= this.totalPage) {
					this.pageIndex++;
					this.getDialogueMsg();
				} else {
					return
				}
			}
			if (this.unreadItem.length > 0) {
				this.observeContent(this.newMsgID);
			}
		},
		methods: {
			init() {
				// // 实例化socket
				this.socket = new WebSocketClass(wsUrl + '?LoginToken=' + getToken());
				// 监听socket消息
				this.socket.getWebSocketMsg(this.getMessage);

				// if (typeof(WebSocket) === "undefined") {
				// 	this.Toast("您的浏览器不支持socket")
				// } else {
				// 	// 实例化socket
				// 	this.socket = new WebSocket(wsUrl + '?LoginToken=' + getToken())
				// 	// 监听socket连接
				// 	this.socket.onopen = this.open
				// 	// 监听socket错误信息
				// 	this.socket.onerror = this.error
				// 	// 监听socket消息
				// 	this.socket.onmessage = this.getMessage
				// }
			},
			open: function() {
				// console.log("socket连接成功")
			},
			error: function() {
				console.log("连接错误")
			},
			getMessage: function(msg) {
				console.log(msg)
				if (msg) {
					const {
						Data,
						ExcuteResult
					} = msg;
					if (Data) {
						// 发送方必须是当前聊天方,接收方必须是本人
						if (Data.SendObjectID == this.touserid && Data.ReciveObjectID == this.userinfo.userID) {
							let info = {
								messageContent: Data.MessageContent,
								messageID: Data.MessageID,
								messageState: 0,
								messageTime: formatDate(Data.MessageTime, "yyyy-MM-dd"),
								messageType: Data.MessageType,
								reciveHeadpic: '',
								reciveObjectID: Data.ReciveObjectID,
								recivenickname: "",
								sendHeadpic: Data.SendHeadpic,
								sendObjectID: Data.SendObjectID,
								sendnickname: Data.Sendnickname,
								sessionNo: Data.SessionNo
							};
							this.listArr.push(info);
							// 缓存聊天记录
							uni.setStorageSync(this.touserid + '/' + this.userinfo.userID,JSON.stringify(this.listArr));
							// 当添加新数据时 总条数小于10条 滑动到顶部
							if (this.listArr.length < 10) {
								// 滑动到顶部
								this.scrollToBottom(0);
							}
						}
					}
				}
			},
			close: function() {
				console.log("socket已经关闭")
			},
			//////////////////////////////////////////////////// 事件监听 //////////////////////////////////////////////////////////////////
			// 监听指定元素是否可视
			observeContent(ID) {
				// 获取可视高度
				let windowHeight = uni.getSystemInfoSync().windowHeight - 100;
				// 获取指定元素高度
				let view = uni.createSelectorQuery().select('.delI' + ID);
				view.boundingClientRect(v => {
					// 监听元素距顶部的高度是否大于 可视区高度
					if (v.top > windowHeight) {
						this.unreadNumber = this.unreadItem.length;
					} else {
						this.listArr.map(item => {
							if (item.messageID == ID) {
								item['messageState'] = 1;
							}
						});
						this.isUnreadItem(this.listArr);
					}
				}).exec();
			},
			// 监听数组是否有未读消息
			isUnreadItem(arr) {
				this.unreadItem = arr.filter(item => {
					if (item.messageState == 0) {
						return item;
					}
				}) || []
				// 如果有未读消息 则监听未读消息元素是否可视
				if (this.unreadItem.length > 0) {
					this.newMsgID = this.unreadItem[0].messageID;
					setTimeout(() => {
						this.observeContent(this.newMsgID);
					}, 200)
				} else {
					this.unreadNumber = 0;
				}
			},
			//////////////////////////////////////////////////// 网络获取 //////////////////////////////////////////////////////////////////
			// 获取缓存聊天记录
			getChatRecord(touserid){
				uni.getStorage({
					key: touserid + "/" + this.userinfo.userID,
					success: (res) => {
						this.listArr = JSON.parse(res.data);
					}
				})
			},
			// 获取对话列表
			async getDialogueMsg() {
				const {
					data
				} = await GetMsg({
					touserid: this.touserid,
					PageIndex: this.pageIndex,
					PageSize: this.PageSize,
				});
				this.isLoading = false;
				if (!isEmpty(data)) {
					const {
						list,
						totalPage
					} = data;
					this.totalPage = totalPage;

					// 生成VIEW_ID,大写,避免污染源数据
					list.forEach(val => {
						val.VIEW_ID = "msg" + val.messageID // 不以数字开头
					})
					// 获取当前最顶部的VIEW_ID (注意是写在设置列表数据前面)
					let topMsg = this.listArr[0]

					//设置列表数据
					if (this.pageIndex <= 1) {
						this.listArr = list;
						// 当刷新或者初始化时，得到最新的一条数据
						let bottomMsg = list[list.length - 1];
						this.newMsgID = bottomMsg.messageID;
						this.unreadNumber = 0;
					} else {
						this.listArr = [...list, ...this.listArr];
					}
					console.log(this.listArr);

					// 设置滚动条位置
					this.$nextTick(() => {
						if (this.pageIndex <= 1 && this.listArr.length >= 10) {
							// 第一页并且数据条数大于10 直接滚动到底部
							this.scrollToBottom(9999);
						} else if (topMsg) {
							// 保持顶部消息的位置
							let view = uni.createSelectorQuery().select('#' + topMsg.VIEW_ID);
							view.boundingClientRect(v => {
								// console.log("节点离页面顶部的距离=" + v.top);
								this.scrollToBottom(v.top - 100); // 减去上偏移量100
							}).exec();
						} else {
							this.scrollToBottom(0);
						}
					})
				}
			},
			// 发送消息
			async submit(type) {
				let msgContent = type == 1 ? this.msg : this.img;
				if (!this.msg && !this.img) {
					return this.Toast('请输入发送内容');
				}
				let data = {
					touserid: this.touserid,
					msg: msgContent,
					type: type
				}
				const {
					success
				} = await sendMsg(data); // 发送消息
				if (success) {
					let info = {
						messageContent: msgContent,
						messageID: 0,
						messageState: 1,
						messageTime: formatDate(new Date(), "yyyy-MM-dd"),
						messageType: type,
						reciveHeadpic: "",
						reciveObjectID: this.touserid,
						recivenickname: this.touserName,
						sendHeadpic: this.userinfo.userAvatarUrl,
						sendObjectID: this.userinfo.userID,
						sendnickname: this.userinfo.nickName,
						sessionNo: ""
					};
					this.listArr.push(info);
					console.log(this.listArr);
					// 缓存聊天记录
					uni.setStorageSync(this.touserid + '/' + this.userinfo.userID,JSON.stringify(this.listArr));
					// 当发送新消息时  总数据小于10条  滑动到顶部  否则底部
					if (this.listArr.length < 10) {
						// 滑动到顶部
						this.scrollToBottom(0);
					} else {
						// 滑动到底部
						this.scrollToBottom(9999);
					}
					this.msg = '';
					this.img = '';
				}
			},
			// 上传图片
			addPhoto() {
				let that = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: async function({
						tempFilePaths,
						tempFiles
					}) {
						uni.showLoading();
						tempFiles[0].FileName = tempFiles[0]['name'];
						// console.log(tempFiles)
						const {
							success,
							errorMessage,
							data
						} = await UploadImageFile(tempFilePaths[0], tempFiles);
						if (success) {
							console.log(data)
							that.img = data;
							that.submit(2);
						} else {
							this.Toast(errorMessage);
							// 当发送新消息时  总数据小于10条  滑动到顶部  否则底部
							if (this.listArr.length < 10) {
								// 滑动到顶部
								this.scrollToBottom(0);
							} else {
								// 滑动到底部
								this.scrollToBottom(9999);
							}
							return;
						}
						uni.hideLoading()
					},
					fail() {
						// 当发送新消息时  总数据小于10条  滑动到顶部  否则底部
						if (this.listArr.length < 10) {
							// 滑动到顶部
							this.scrollToBottom(0);
						} else {
							// 滑动到底部
							this.scrollToBottom(9999);
						}
					}
				});

			},
			// 全部标为已读
			async ReadAll() {
				const {
					success
				} = await ReadAll({
					touserid: this.touserid
				});
			},
			// 设置滚动条滑动到指定高度
			scrollToBottom(scrollTop) {
				this.$nextTick(function() {
					setTimeout(() => {
						uni.pageScrollTo({
							scrollTop: scrollTop,
							duration: 0
						})
					}, 100) // 要加点延迟, 不然有可能不生效
				});
			}
		}
	}
</script>

<style lang="scss">
	.dialogue {

		.msg-end {
			font-size: 24rpx;
			font-family: PingFang SC-Regular, PingFang SC;
			font-weight: 400;
			color: #999999;
			text-align: center;
		}

		.dleUnread {
			position: fixed;
			right: 0;
			bottom: 150rpx;
			background: #FFFFFF;
			padding: 15rpx 25rpx;
			border: 1rpx solid #EEEEEE;
			border-top-left-radius: 40rpx;
			border-bottom-left-radius: 40rpx;
			color: #FA2B47;
		}

		.footers {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;

			padding: 18rpx 24rpx;
			background: #FFFFFF;
			box-sizing: border-box;

			.input_v {
				flex: 1;
				background: #F6F6F6;
				border-radius: 200rpx;
				padding: 15rpx 41rpx;

				.dle_input {
					width: unset;
				}

				.placeholderClass {
					font-size: 28rpx;
					font-weight: 400;
					color: #999999;
				}
			}


			.m-button {
				margin-left: 20rpx;
				padding: 12rpx 24rpx;
				font-size: 28rpx;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
			}
		}
	}
</style>
